//
//  TestViewController.m
//  EGUC
//
//  Created by 王译 on 17/2/8.
//
//

#import "TestViewController.h"
#import "VidyoClientConstants.h"
#import "VidyoClientMessages.h"
#import "VidyoClient.h"
#import "NSString+Base64.h"
#import "VidyoClientSample.h"
#import "LoginModel.h"
#import <WebKit/WebKit.h>

@interface TestViewController ()<UIWebViewDelegate>
{
    NSString *userPortal;
    NSString *userName;
    NSString *passWord;
    UIWebView *webView;
}
@end

@implementation TestViewController

@synthesize webData, soapResults, xmlParser;
@synthesize vidyoEntityID, vidyoMemberStatus, vidyoClientStatus;
@synthesize signingInAlert, isSigningIn;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    userPortal = @"http://viviuc.com";
    userName = @"10013";
    passWord = @"egoo";
   // userName = @"sunsiyuan";
    //passWord = @"222222";
    [self createWebView];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createButton];
    // Do any additional setup after loading the view.
}




-(void)createWebView{
    webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 300, self.view.frame.size.width, 400)];
    webView.delegate = self;
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *baseURL = [[NSBundle mainBundle] bundleURL];
    [webView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];
    [self.view addSubview:webView];
}


-(void)showVidyoWeb{
    
    

    entityIDResult = FALSE;
    memberStatusResult = FALSE;
    joinStatus = FALSE;
    vidyoMemberStatus = nil;
    
    VidyoClientInEventRoomLink event = {0};
    //最重要的地方.
    NSString *guestVPortal = @"http://viviuc.com";
   // NSString *guestVName = @"test";
    
    NSString *guestVRoomPin =@"wangyi";
    
    LoginModel *model = [LoginModel sharedInstance].userArr[0];
    NSString *guestVName = model.userId;
    
    strlcpy(event.portalUri, [guestVPortal UTF8String], sizeof(event.portalUri));
//    strlcpy(event.roomKey, [guestVRoomKey UTF8String], sizeof(event.roomKey));
    strlcpy(event.roomKey, [self.guestVRoomKey UTF8String], sizeof(event.roomKey));
    strlcpy(event.displayName, [guestVName UTF8String], sizeof(event.displayName));
    strlcpy(event.pin, [guestVRoomPin UTF8String], sizeof(event.pin));
    
    // hide keyboard
    [self.view endEditing:TRUE];
    
    if (VidyoClientSendEvent(VIDYO_CLIENT_IN_EVENT_ROOM_LINK, &event, sizeof(VidyoClientInEventRoomLink)) == false)
    {
        [signingInAlert dismissWithClickedButtonIndex:0 animated:YES];
        
        NSString *alertMsg = [NSString stringWithFormat:@"Failed to sign in"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMsg message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        
    }
    else
    {
        _isInCall = true;
        isSigningIn = TRUE;
    }
}

-(void)showVidyo{
    //测试屏幕大小代码
    VidyoClientInEventVideoFrame frame = {0};
    frame.width = 100;
    frame.height = 100;
    
    entityIDResult = FALSE;
    memberStatusResult = FALSE;
    joinStatus = FALSE;
    vidyoMemberStatus = nil;
    
    VidyoClientInEventRoomLink event = {0};
    //最重要的地方.
    NSString *guestVPortal = @"http://viviuc.com";
    //NSString *guestVRoomKey = @"73KOZC5T5OnrKq6jX5lYHbEdfQM";
    
    LoginModel *model = [LoginModel sharedInstance].userArr[0];
    NSString *guestVName = model.userId;
    
    NSString *guestVRoomPin =@"wangyi";
    
    
    strlcpy(event.portalUri, [guestVPortal UTF8String], sizeof(event.portalUri));
    strlcpy(event.roomKey, [self.guestVRoomKey UTF8String], sizeof(event.roomKey));
    strlcpy(event.displayName, [guestVName UTF8String], sizeof(event.displayName));
    strlcpy(event.pin, [guestVRoomPin UTF8String], sizeof(event.pin));
    
    // hide keyboard
    [self.view endEditing:TRUE];
    
    if (VidyoClientSendEvent(VIDYO_CLIENT_IN_EVENT_ROOM_LINK, &event, sizeof(VidyoClientInEventRoomLink)) == false)
    {
        [signingInAlert dismissWithClickedButtonIndex:0 animated:YES];
        
        NSString *alertMsg = [NSString stringWithFormat:@"Failed to sign in"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMsg message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        
    }
    else
    {
        _isInCall = true;
        isSigningIn = TRUE;
    }
}

-(void)createButton{
    
    UIButton *myRoomButton = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    [myRoomButton setTitle:@"我的会议室" forState:UIControlStateNormal];
    myRoomButton.backgroundColor = [UIColor greenColor];
    [myRoomButton addTarget:self action:@selector(joinMyRoomBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myRoomButton];
    
    UIButton *loginVidyoPortalBtn = [[UIButton alloc]initWithFrame:CGRectMake(200, 200, 100, 100)];
    [loginVidyoPortalBtn setTitle:@"登录Portal" forState:UIControlStateNormal];
    loginVidyoPortalBtn.backgroundColor = [UIColor yellowColor];
    [loginVidyoPortalBtn addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginVidyoPortalBtn];
}

-(void)login{
    entityIDResult = FALSE;
    memberStatusResult = FALSE;
    joinStatus = FALSE;
    vidyoMemberStatus = nil;
    
    VidyoClientInEventLogIn event = {0};
    
#warning 待修改
    userPortal = @"http://viviuc.com";
    userName = @"10013";
    passWord = @"egoo";
    
    NSString *userVPortal = userPortal;
    NSString *userVName = userName;
    NSString *userVPass = passWord;
    
    strlcpy(event.portalUri, [userVPortal UTF8String], sizeof(event.portalUri));
    strlcpy(event.userName, [userVName UTF8String], sizeof(event.userName));
    strlcpy(event.userPass, [userVPass UTF8String], sizeof(event.userPass));
    
    // hide keyboard
    
    /* Create wait alert */
    
    
    
    // send login-event to VidyoClient
    if (VidyoClientSendEvent(VIDYO_CLIENT_IN_EVENT_LOGIN, &event, sizeof(VidyoClientInEventLogIn)) == false)
    {
        [signingInAlert dismissWithClickedButtonIndex:0 animated:YES];
        
        NSString *alertMsg = [NSString stringWithFormat:@"Failed to sign in"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMsg message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        NSLog(@"登录失败");
        [MBProgressHUD showErrorMessage:@"登录失败"];
    }
    else
    {
        isSigningIn = TRUE;
        NSLog(@"登陆成功");
        [MBProgressHUD showSuccessMessage:@"登录成功"];
    }
}

-(void)join{
    vidyoEntityID = nil;
#warning 待修改
    userPortal = @"http://viviuc.com";
    userName = @"10013";
    passWord = @"egoo";
    
    NSString *urlString = [NSString stringWithFormat:@"%@/services/v1_1/VidyoPortalUserService", userPortal];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    
    // Get the EntityId from VidyoPortal using WS User::myAccount
    NSString *soapMessage = [NSString stringWithFormat:
                             @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                             "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ns1=\"http://portal.vidyo.com/user/v1_1\">"
                             "<env:Body>"
                             "<ns1:MyAccountRequest/>"
                             "</env:Body>"
                             "</env:Envelope>"];
    
    // NSLog(@"%@", soapMessage);
    
    NSString *msgLength = [NSString stringWithFormat:@"%lu",(unsigned long)[soapMessage length]];
    [theRequest addValue: @"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest addValue: @"myAccount" forHTTPHeaderField:@"SOAPAction"];
    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    
    NSString *base64 = [[NSString stringWithFormat:@"%@:%@", userName, passWord] base64];
    NSString *auth = [NSString stringWithFormat:@"Basic %@", base64];
    [theRequest addValue: auth forHTTPHeaderField:@"Authorization"];
    
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if( theConnection )
    {
        webData = [NSMutableData data];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }
    
    joinStatus = TRUE;
    NSLog(@"*********************SENT SOAP Request myAccount() ******************************");
}

//登录之后可无限制访问会议室
-(void)login:(id)sender{
    
    [self login];
}

-(void)joinMyRoomBtn:(id)sender{
    [self join];
}



- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSDictionary *dictionary = message.body;
    
    /* NSString * vidyoPortal = dictionary[@"vidyoPortal"];
     NSString * vidyoPortal = dictionary[@"roomKey"];
     NSString * userName = dictionary[@"userName"];
     NSString * password = dictionary[@"password"];*/
    
    
    // Initaite the local sign in process
    VidyoClientInEventRoomLink event = {0};
    NSString *guestVPortal = dictionary[@"vidyoPortal"];
    NSString *guestVRoomKey = dictionary[@"roomKey"];
    NSString *guestVName = dictionary[@"password"];
    
    NSString *guestVRoomPin =dictionary[@"roomKey"];
  //这里需要注意
    strlcpy(event.portalUri, [guestVPortal UTF8String], sizeof(event.portalUri));
    strlcpy(event.roomKey, [guestVRoomKey UTF8String], sizeof(event.roomKey));
    strlcpy(event.displayName, [guestVName UTF8String], sizeof(event.displayName));
    strlcpy(event.pin, [guestVRoomPin UTF8String], sizeof(event.pin));
    
    // hide keyboard
    [self.view endEditing:TRUE];
    
    if (VidyoClientSendEvent(VIDYO_CLIENT_IN_EVENT_ROOM_LINK, &event, sizeof(VidyoClientInEventRoomLink)) == false)
    {
        [signingInAlert dismissWithClickedButtonIndex:0 animated:YES];
        
        NSString *alertMsg = [NSString stringWithFormat:@"Failed to sign in"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMsg message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        
    }
    else
    {
        isSigningIn = TRUE;
    }

}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR with theConenction");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"DONE. Received Bytes: %lu", (unsigned long)[webData length]);
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", theXML);
    
    
    
    xmlParser = [[NSXMLParser alloc] initWithData: webData];
    [xmlParser setDelegate: self];
    [xmlParser setShouldResolveExternalEntities: YES];
    [xmlParser parse];
    
    
    // NSLog(@"entityID = %@", vidyoEntityID);
    /* Step2: Send the joinConference if the status is online */
    if ( joinStatus )
    {
        NSString *urlString = [NSString stringWithFormat:@"%@/services/v1_1/VidyoPortalUserService", userPortal];
        NSURL *url = [NSURL URLWithString:urlString];
        NSMutableURLRequest *theJoinRequest = [NSMutableURLRequest requestWithURL:url];
        
        // Get the EntityId from VidyoPortal using WS User::myAccount
        
        NSString *soapJoinMessage = [NSString stringWithFormat:
                                     @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                                     "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ns1=\"http://portal.vidyo.com/user/v1_1\">"
                                     "<env:Body>"
                                     "<ns1:JoinConferenceRequest>"
                                     "<ns1:conferenceID>%@</ns1:conferenceID>"
                                     "</ns1:JoinConferenceRequest>"
                                     "</env:Body>"
                                     "</env:Envelope>", vidyoEntityID];
        
        // NSLog(@"%@", soapJoinMessage);
        
        NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapJoinMessage length]];
        
        [theJoinRequest addValue: @"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [theJoinRequest addValue: @"joinConference" forHTTPHeaderField:@"SOAPAction"];
        [theJoinRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
#warning
        NSString *base64 = [[NSString stringWithFormat:@"%@:%@",userName,passWord] base64];
        NSString *auth = [NSString stringWithFormat:@"Basic %@", base64];
        [theJoinRequest addValue: auth forHTTPHeaderField:@"Authorization"];
        [theJoinRequest setHTTPMethod:@"POST"];
        [theJoinRequest setHTTPBody: [soapJoinMessage dataUsingEncoding:NSUTF8StringEncoding]];
        
        NSURLConnection *theJoinConnection = [[NSURLConnection alloc] initWithRequest:theJoinRequest delegate:self];
        if( theJoinConnection )
        {
            webData = [NSMutableData data];
        }
        else
        {
            NSLog(@"theConnection is NULL");
        }
        
        joinStatus = FALSE;
        NSLog(@"*********************SENT SOAP Request joinConference() ******************************/n");
    }
    
}

- (NSString*) getElementFromElementName: (NSString *) elementName
{
    NSArray *split = [elementName componentsSeparatedByString:@":"];
    if (!split || ([split count] != 2))
    {
        NSLog(@"Not a valid elementName '%@'", elementName);
        return NULL;
    }
    NSString *element = [split objectAtIndex:1];
    if (!element)
    {
        NSLog(@"Element is null");
        return NULL;
    }
    return [NSString stringWithString:element];
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
   attributes: (NSDictionary *)attributeDict
{
    NSString *element = [self getElementFromElementName:elementName];
    if (!element)
    {
        return;
    }
    /* separate namespace from element name */
    if( [element isEqualToString:@"entityID"])
    {
        if(!vidyoEntityID)
        {
            vidyoEntityID = [[NSMutableString alloc] initWithCapacity:256];
        }
        entityIDResult = TRUE;
    }
    else if( [element isEqualToString:@"MemberStatus"])
    {
        if(!vidyoMemberStatus)
        {
            vidyoMemberStatus = [[NSMutableString alloc] initWithCapacity:256];
        }
        memberStatusResult = TRUE;
        
    }
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if( entityIDResult )
    {
        [vidyoEntityID appendString: string];
        entityIDResult = FALSE;
        // NSLog(@"entityID = %@", vidyoEntityID);
    }
    else if (memberStatusResult)
    {
        [vidyoMemberStatus appendString: string];
        memberStatusResult = FALSE;
        
        // NSLog(@"Endpoint is %@", vidyoMemberStatus);
        if(![vidyoMemberStatus isEqualToString:@"Online"])
        {
            joinStatus = FALSE;
            
            // Show the alert with the XML that was received
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *alertMsg = [NSString stringWithFormat:@"User NOT online. Make sure User is Logged In"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMsg message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [alert show];
                
            });
        }
    }
    
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSString *element = [self getElementFromElementName:elementName];
    if (!element)
    {
        return;
    }
    
    if( [element isEqualToString:@"MyAccountResponse"])
    {
        entityIDResult = FALSE;
    }
}


#pragma mark - WebViewDelegate -

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    
    //OC调用JS是基于协议拦截实现的 下面是相关操作
    NSString *absolutePath = request.URL.absoluteString;
    
    NSString *scheme = @"rrcc://";
    
    if ([absolutePath hasPrefix:scheme]) {
        NSString *subPath = [absolutePath substringFromIndex:scheme.length];
        
        if ([subPath containsString:@"?"]) {//1个或多个参数
            
            if ([subPath containsString:@"&"]) {//多个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                NSArray *params = [parameter componentsSeparatedByString:@"&"];
                
                if (params.count == 2) {
                    if ([self respondsToSelector:sel]) {
                        [self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
                    }
                }
                
                
            } else {//1个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                
                if ([self respondsToSelector:sel]) {
                    [self performSelector:sel withObject:parameter];
                }
                
            }
            
        } else {//没有参数
            NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            SEL sel = NSSelectorFromString(methodName);
            
            if ([self respondsToSelector:sel]) {
                [self performSelector:sel];
            }
        }
    }
    
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
